﻿Imports WRDB.Project

''' <summary>
''' Allow user to select table or import file for importing
''' </summary>
''' <remarks>
''' This form utilizes the ExplorerTree control available at: http://www.codeproject.com/KB/miscctrl/ExplorerTree.aspx
''' It also demonstrates how WRDB DLLs are dynamically loaded at runtime from their installation folder (so they don't have
''' to be distributed again with EPDRiv1)
''' </remarks>
Public Class frmSelectTable

    Public Enum enumProjectType
        WRDB6
        WRDB5
        WRDB4
        External
        File
    End Enum

    Public Enum enumTableType
        Working
        Master
    End Enum

    Public InitialDatabaseFile As String = ""

    Private _SelectedTables As Generic.List(Of clsTable)
    Private _BaseFileName As String
    Private _ExpertMode As String

    Private TabInitialized As Boolean() = {False, False, False}

    Private _SuspendGetFiles As Boolean = True

    ''' <summary>
    ''' Instantiate form
    ''' </summary>
    ''' <param name="BaseFileName">Name of graph group file (or any file which indicates alternate directory to search tables for)</param>
    ''' <param name="ExpertMode">Expert mode setting (suppresses some warnings if true)</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal BaseFileName As String, ExpertMode As Boolean)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        _BaseFileName = BaseFileName
        _ExpertMode = ExpertMode
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            Cursor = Cursors.WaitCursor
            Application.DoEvents()
            _SelectedTables = New Generic.List(Of clsTable)
            Dim tbl As New clsTable(_BaseFileName, _ExpertMode)
            Select Case SelectedProjectType
                Case enumProjectType.WRDB6, enumProjectType.WRDB5, enumProjectType.WRDB4 'enumerations have different values!
                    If Not tbl.CreateWRDBTable(SelectedProjectName, Choose(SelectedProjectType + 1, clsTable.enumTableType.WRDB6, clsTable.enumTableType.WRDB5, clsTable.enumTableType.WRDB4)) Then Exit Sub
                    tbl.TableName = tbl.WRDBProject.FullTableName(SelectedTableName)
                    _SelectedTables.Add(tbl)
                Case enumProjectType.External
                    If Not tbl.CreateExternalTable(SelectedProjectName, SelectedTableName) Then Exit Sub
                    'tbl.TableName = tbl.WRDBProject.FullTableName(SelectedTableName)
                    _SelectedTables.Add(tbl)
                Case enumProjectType.File
                    Select Case IO.Path.GetExtension(SelectedTableName.ToUpper)
                        Case ".BMD"
                            If Not tbl.CreateBMDTable(SelectedProjectName & "\" & SelectedTableName) Then Exit Sub
                            tbl.TableName = SelectedTableName
                            _SelectedTables.Add(tbl)
                        Case ".BMD2"
                            If Not tbl.CreateBMD2Table(SelectedProjectName & "\" & SelectedTableName) Then Exit Sub
                            tbl.TableName = SelectedTableName
                            _SelectedTables.Add(tbl)
                        Case ".TXT", ".CSV", ".DBF", ".DB"
                            If Not tbl.CreateDatabaseFileTable(SelectedProjectName, SelectedTableName) Then Exit Sub
                            _SelectedTables.Add(tbl)
                        Case ".OUT", ".AIR", ".WDM", ".HBN", ".TS"
                            If Not tbl.CreateWRDBDataTable(SelectedProjectName & "\" & SelectedTableName) Then Exit Sub
                            _SelectedTables.Add(tbl)
                        Case ".DSS"
                            For Each SelectedDataset As String In SelectedDatasets
                                Dim tbl2 As New clsTable(_BaseFileName, _ExpertMode)
                                If Not tbl2.CreateWRDBDataTable(SelectedProjectName & "\" & SelectedTableName, SelectedDataset) Then Exit Sub
                                tbl2.TableName = SelectedDataset
                                _SelectedTables.Add(tbl2)
                            Next
                        Case Else
                            For Each SelectedDataset As String In SelectedDatasets
                                Dim tbl2 As New clsTable(_BaseFileName, _ExpertMode)
                                If Not tbl2.CreateDatabaseFileTable(SelectedProjectName & "\" & SelectedTableName, SelectedDataset) Then Exit Sub
                                tbl2.TableName = SelectedDataset
                                _SelectedTables.Add(tbl2)
                            Next
                    End Select
                    'If SelectedDataset <> "" Then
                    '    tbl.TableName = tbl.WRDBProject.FullTableName(tbl.TableName)
                    'End If
            End Select
            Close()
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        _SelectedTables = Nothing
        Close()
    End Sub

    Private Sub cboFileTypes_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboFileTypes.SelectedIndexChanged
        GetFiles()
        btnOK.Enabled = False
    End Sub

    Private Sub dgWRDB_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgWRDB.SelectionChanged, dgExternal.SelectionChanged
        GetTables(sender)
        btnOK.Enabled = False
    End Sub

    Private Sub ExplorerTree1_PathChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExplorerTree1.PathChanged
        If _SuspendGetFiles Then Exit Sub
        GetFiles()
        btnOK.Enabled = False
    End Sub

    Private Sub frmSelectTable_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        SaveSetting(REGAPP, Me.Name, "InitialTab", TabControl1.SelectedIndex)
        If dgWRDB.SelectedCells.Count <> 0 Then SaveSetting(REGAPP, Me.Name, "WRDBProject", dgWRDB.SelectedCells(0).Value & vbTab & dgWRDB.SelectedCells(1).Value)
        If dgExternal.SelectedCells.Count <> 0 Then SaveSetting(REGAPP, Me.Name, "Connection", dgExternal.SelectedCells(0).Value)
        'do not save paths to network shares; when try to restore on next form load, gives untrappable error message
        If Not ExplorerTree1.SelectedPath.StartsWith("\\") Then SaveSetting(REGAPP, Me.Name, "BrowserPath", ExplorerTree1.SelectedPath)
        SaveSetting(REGAPP, Me.Name, "Splitter", SplitContainer1.SplitterDistance)
        SaveSetting(REGAPP, Me.Name, "FileType", cboFileTypes.SelectedIndex)
        SaveSetting(REGAPP, Me.Name, "Tablename", lstTables.Text)
        SaveWindowPos(REGAPP, Me)
    End Sub

    Private Sub frmSelectTable_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            GetWindowPos(REGAPP, Me)
            With cboFileTypes.Items
                .Clear()
                .AddRange(New String() {"All Import Formats",
                                        "Binary Modeling Data Files (*.bmd)",
                                        "Binary Modeling Data Files Ver 2 (*.bmd2)",
                                        "Paradox (WRDB) Tables (*.db)",
                                        "dBase Tables (*.dbf)",
                                        "Excel Workbook Files (*.xls*)",
                                        "Tab-delimited Text Files (*.txt)",
                                        "Comma-separated Text Files (*.csv)",
                                        "COE Data Storage System Files (*.dss)",
                                        "Watershed Data Management Files (*.wdm)",
                                        "HSPF Binary Output Files (*.hbn)",
                                        "GSSHA Time Series Files (*.ts)",
                                        "LSPC Output Files (*.out)",
                                        "LSPC Input Files (*.air)",
                                        "Access Database Files (*.mdb)",
                                        "Firebird Database Files (*.fdb)",
                                        "SQLite Database Files (*.sdb)",
                                        "SQL Server CE Database Files (*.sdf)"})
            End With

            'remember split position
            SplitContainer1.SplitterDistance = Val(GetSetting(REGAPP, Name, "Splitter", SplitContainer1.SplitterDistance))

            cboFileTypes.SelectedIndex = GetSetting(REGAPP, Me.Name, "FileType", 0)
            If TabControl1.SelectedIndex = 2 Then lstTables.SelectedIndex = GetSetting(REGAPP, Me.Name, "Filename", "")

            btnOK.Enabled = False

        Catch ex As Exception

            ErrorMsg(, ex)

        End Try

    End Sub

    Private Sub frmSelectTable_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        'set initial tab
        Me.TabControl1.SelectedIndex = -1
        Me.TabControl1.SelectedIndex = Math.Max(0, Math.Min(Me.TabControl1.TabCount - 1, Val(GetSetting(REGAPP, Me.Name, "InitialTab", "0"))))
        _SuspendGetFiles = False
        GetProjects()
        lstTables.Text = GetSetting(REGAPP, Me.Name, "Tablename", "")

        If InitialDatabaseFile <> "" And My.Computer.FileSystem.FileExists(InitialDatabaseFile) Then
            TabControl1.SelectedIndex = 2
            ExplorerTree1.SelectedPath = IO.Path.GetDirectoryName(InitialDatabaseFile)
            ExplorerTree1.btnGo_Click(Me, New System.EventArgs)
            Application.DoEvents()
            lstTables.Text = IO.Path.GetFileName(InitialDatabaseFile)
        End If

    End Sub

    Private Sub GetFiles()
        If _SuspendGetFiles OrElse cboFileTypes.SelectedIndex = -1 Then Exit Sub
        lstTables.Items.Clear()
        Dim extensions() As String = {"*.bmd", "*.bmd2", "*.db", "*.dbf", "*.xls*", "*.txt", "*.csv", "*.dss", "*.wdm", "*.hbn", "*.ts", "*.out", "*.air", "*.mdb", "*.fdb", "*.sdb", "*.sdf"}
        Dim imin, imax As Integer
        If cboFileTypes.SelectedIndex = 0 Then
            imin = 0
            imax = extensions.Length - 1
        Else
            imin = cboFileTypes.SelectedIndex - 1
            imax = imin
        End If
        For i As Integer = imin To imax
            For Each File As String In IO.Directory.GetFiles(ExplorerTree1.SelectedPath, extensions(i), IO.SearchOption.TopDirectoryOnly)
                'If IO.Path.GetExtension(File).ToLower = extensions(i).Replace("*", "") Then lstTables.Items.Add(IO.Path.GetFileName(File)) 'this is necessary because *.bmd also matches files with *.bmd2
                If IO.Path.GetExtension(File).ToLower Like extensions(i) Then lstTables.Items.Add(IO.Path.GetFileName(File)) 'this is necessary because *.bmd also matches files with *.bmd2
            Next
        Next
    End Sub

    Private Sub GetTables(ByVal dg As DataGridView)
        Try
            Cursor = Cursors.WaitCursor
            Application.DoEvents()
            With CType(dg, DataGridView)
                lstTables.Items.Clear()

                If .SelectedRows.Count = 0 OrElse .SelectedCells(0).Value = Nothing Then Exit Sub

                If dg Is dgWRDB Then
                    Select Case dg.SelectedCells(1).Value
                        Case "6.x"
                            Dim Project As clsProject = Nothing
                            Try
                                Project = New clsProject(.SelectedCells(0).Value)
                            Catch ex As Exception
                                WarningMsg("Unable to open WRDB project named '{0}'; detailed error was:\n\n{1}", .SelectedCells(0).Value, ex.ToString)
                                Exit Sub
                            End Try
                            If Project Is Nothing OrElse Project.DB Is Nothing OrElse Not Project.DB.TestConnectionQuick(5) Then
                                WarningMsg("Unable to connect to WRDB project; please check project preferences and that the referenced database is available.")
                                Exit Sub
                            End If
                            Dim tblList As Generic.List(Of String) = Project.GetTableList(clsProject.enumTableTypes.Working)
                            If tblList Is Nothing Then Exit Sub
                            For Each Table As String In tblList
                                lstTables.Items.Add(Table)
                            Next
                            tblList = Project.GetTableList(clsProject.enumTableTypes.Master)
                            If tblList Is Nothing Then Exit Sub
                            For Each Table As String In tblList
                                If Not lstTables.Items.Contains(Table) Then lstTables.Items.Add(Table & " [Master]")
                            Next
                        Case "5.x"
                            Dim Project As clsProject = Nothing
                            Try
                                Dim ProjName As String = .SelectedCells(0).Value
                                Project = New clsProject(ProjName, True)
                                With New clsWRDB5IniFile
                                    If My.Computer.FileSystem.FileExists(.FileName) Then
                                        .SetProjectName(ProjName)
                                        Dim dbType As clsDB.enumDBType = [Enum].Parse(GetType(clsDB.enumDBType), .GetKey(clsWRDB5IniFile.enumSection.Project, clsWRDB5IniFile.enumKey.DatabaseType))
                                        Dim dbSrce As String = clsProject.ReplaceMyDocs(.GetKey(clsWRDB5IniFile.enumSection.Project, clsWRDB5IniFile.enumKey.DataSource))
                                        Dim dbName As String = .GetKey(clsWRDB5IniFile.enumSection.Project, clsWRDB5IniFile.enumKey.DatabaseName)
                                        If Not Project.CreateTempProject(dbType, dbSrce, dbName) Then Exit Sub
                                    End If
                                End With
                            Catch ex As Exception
                                WarningMsg("Unable to open WRDB project named '{0}'; detailed error was:\n\n{1}", .SelectedCells(0).Value, ex.ToString)
                                Exit Sub
                            End Try
                            Dim tblList As Generic.List(Of String) = Project.GetTableList(clsProject.enumTableTypes.Working)
                            If tblList Is Nothing Then Exit Sub
                            For Each Table As String In tblList
                                lstTables.Items.Add(Table)
                            Next
                            tblList = Project.GetTableList(clsProject.enumTableTypes.Master)
                            If tblList Is Nothing Then Exit Sub
                            For Each Table As String In tblList
                                If Not lstTables.Items.Contains(Table) Then lstTables.Items.Add(Table & " [Master]")
                            Next
                        Case "4.x"
                            Dim prjDir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
                            prjDir = prjDir.Substring(0, prjDir.LastIndexOf("\"))
                            Dim prjFile As String = prjDir & "\" & .SelectedCells(0).Value & ".prj"
                            If My.Computer.FileSystem.FileExists(prjFile) Then
                                Dim iniFile As New WRDB.IniFile.clsIniFile(prjFile, False)
                                Dim WorkingDir As String = iniFile.GetKeyText("Settings", "TempPath")
                                Dim MasterDir As String = iniFile.GetKeyText("Settings", "MasterPath")
                                For j As Integer = 1 To 2
                                    For Each File As String In IO.Directory.GetFiles(Choose(j, WorkingDir, MasterDir), "*.db")
                                        If Not lstTables.Items.Contains(IO.Path.GetFileName(File)) Then lstTables.Items.Add(IO.Path.GetFileName(File) & Choose(j, "", " [Master]"))
                                    Next
                                Next j
                            End If
                    End Select
                ElseIf dg Is dgExternal Then
                    lstTables.Items.AddRange(clsConnections.GetMappingTables(.SelectedCells(0).Value).ToArray)
                End If
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            lstTables.Refresh()
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub lstDatasets_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstDatasets.DoubleClick
        If lstDatasets.Text <> "" Then btnOK.PerformClick()
    End Sub

    Private Sub lstTables_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstTables.DoubleClick
        If Not (lstDatasets.Visible And lstDatasets.Enabled) And lstTables.Text <> "" Then btnOK.PerformClick()
    End Sub

    Private Sub lstTables_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstTables.SelectedIndexChanged
        Try
            If TabControl1.SelectedIndex = 2 Then
                If lstTables.SelectedIndex = -1 Then Exit Sub
                lstDatasets.Items.Clear()
                Dim ext As String = IO.Path.GetExtension(SelectedTableName.ToUpper)
                Select Case ext
                    Case ".MDB", ".XLS", ".XLSX", "XLSM", ".SDB", ".FDB", ".SDF", ".DSS"
                        UseWaitCursor = True
                        Application.DoEvents()
                        Dim tbl As New clsTable(_BaseFileName, _ExpertMode)
                        Dim tblList As Generic.List(Of String)
                        Select Case ext
                            Case ".DSS"
                                If Not tbl.CreateWRDBDataTable(SelectedProjectName & "\" & SelectedTableName) Then Exit Sub
                                tblList = tbl.dsData.TableNames
                            Case Else
                                If Not tbl.CreateDatabaseFileTable(SelectedProjectName & "\" & SelectedTableName, "") Then Exit Sub
                                tblList = tbl.WRDBProject.GetTableList(clsProject.enumTableTypes.Working)
                        End Select
                        If tblList Is Nothing Then Exit Sub
                        lstDatasets.Items.AddRange(tblList.ToArray)
                        If lstDatasets.Items.Count > 0 Then lstDatasets.SelectedIndex = 0
                        UseWaitCursor = False
                        grpDatasets.Enabled = True
                    Case Else
                        grpDatasets.Enabled = False
                End Select
                Dim dbFile As String = String.Format("{0}\{1}", SelectedProjectName, SelectedTableName)
                If My.Computer.FileSystem.FileExists(dbFile) Then
                    With My.Computer.FileSystem.GetFileInfo(dbFile)
                        lblFileInfo.Text = String.Format("{0}: {1:#,###,###,###} kB; {2}", SelectedTableName, .Length / 1024, .LastWriteTime.ToString("G"))
                    End With
                End If
            End If
            btnOK.Enabled = lstTables.SelectedIndex <> -1
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            UseWaitCursor = False
        End Try
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        GetProjects()
    End Sub

    Private Sub GetProjects()
        Try
            If TabControl1.SelectedIndex = -1 Then Exit Sub
            If Not TabInitialized(TabControl1.SelectedIndex) Then
                Select Case TabControl1.SelectedIndex
                    Case 0
                        With dgWRDB
                            .ClearSelection()
                            .Rows.Clear()
                            .ColumnCount = 4
                            .ColumnHeadersVisible = True
                            .RowHeadersVisible = False
                            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                            .Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
                            .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
                            .Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                            .Columns(3).Visible = False  'will hold sorting key only (want 6 then 5 then 4)
                            .Columns(0).HeaderText = "Name"
                            .Columns(1).HeaderText = "Version"
                            .Columns(2).HeaderText = "Description"
                            .Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
                            .Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
                            .Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
                            .Columns(1).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                            .AllowUserToResizeRows = False
                            .AllowUserToResizeColumns = False
                            .AllowUserToOrderColumns = False
                            .AllowUserToDeleteRows = False
                            .AllowUserToAddRows = False
                            .ReadOnly = True
                            .MultiSelect = False
                            .DefaultCellStyle.Font = New Font("Tahoma", 8.5, FontStyle.Regular, GraphicsUnit.Point)

                            If TabControl1.SelectedIndex = 0 Then
                                'add WRDB 6 projects
                                For Each kv As Generic.KeyValuePair(Of String, String) In clsConnections.GetProjectList
                                    .Rows.Add(kv.Key, "6.x", kv.Value, "1" & kv.Key)
                                Next

                                'add WRDB 5 projects
                                With New clsWRDB5IniFile
                                    If My.Computer.FileSystem.FileExists(.FileName) Then
                                        For Each s As String In .GetProjectNames
                                            .SetProjectName(s)
                                            dgWRDB.Rows.Add(s, "5.x", .GetKey(clsWRDB5IniFile.enumSection.Project, clsWRDB5IniFile.enumKey.Description), "2" & s)
                                        Next
                                    End If
                                End With

                                'add WRDB 4 projects
                                Dim prjDir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
                                prjDir = prjDir.Substring(0, prjDir.LastIndexOf("\"))

                                If My.Computer.FileSystem.FileExists(prjDir & "\WRDB.INI") Then
                                    Dim iniFile As New IniFile.clsIniFile(prjDir & "\WRDB.INI", False)
                                    With iniFile
                                        Dim NumProjects As Int16 = Val(.GetKeyText("WRDB", "NumProjects"))
                                        For i As Int16 = 1 To NumProjects
                                            Dim Name As String = .GetKeyText("WRDB", "ProjectName" & i)
                                            Dim Desc As String = .GetKeyText("WRDB", "ProjectDesc" & i)
                                            dgWRDB.Rows.Add(Name, "4.x", Desc, "3" & Name)
                                        Next
                                    End With
                                End If

                                .Sort(.Columns(3), System.ComponentModel.ListSortDirection.Ascending)

                                For r As Integer = 0 To .RowCount - 1
                                    If .Item(0, r).Value & vbTab & .Item(1, r).Value = GetSetting(REGAPP, Me.Name, "WRDBProject", "") Then
                                        .Rows(r).Selected = True
                                        .FirstDisplayedCell = .Item(0, r)
                                    End If
                                Next

                            Else
                                Dim prjDir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
                                prjDir = prjDir.Substring(0, prjDir.LastIndexOf("\"))

                                If My.Computer.FileSystem.FileExists(prjDir & "\WRDB.INI") Then
                                    Dim IniFile As New WRDB.IniFile.clsIniFile(prjDir & "\WRDB.INI", False)

                                    Dim NumProjects As Integer = Val(IniFile.GetKeyText("WRDB", "NumProjects"))
                                    For j As Integer = 1 To NumProjects
                                        Dim Name As String = IniFile.GetKeyText("WRDB", "ProjectName" & j)
                                        Dim Desc As String = IniFile.GetKeyText("WRDB", "ProjectDesc" & j)
                                        Dim prjFile As New WRDB.IniFile.clsIniFile(prjDir & "\" & Name & ".prj", False)
                                        Dim WorkingDir As String = prjFile.GetKeyText("Settings", "TempPath")
                                        Dim MasterDir As String = prjFile.GetKeyText("Settings", "MasterPath")
                                        .RowCount += 1
                                        .Item(0, .RowCount - 1).Value = Name
                                        .Item(1, .RowCount - 1).Value = Desc
                                        .Item(2, .RowCount - 1).Value = WorkingDir
                                        .Item(3, .RowCount - 1).Value = MasterDir
                                    Next
                                    .Sort(.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
                                    Dim LastProject As String = GetSetting(REGAPP, Me.Name, "WRDB4Project", "")
                                    For r As Integer = 0 To .RowCount - 1
                                        If .Item(0, r).Value = LastProject Then .Rows(r).Selected = True : Exit For
                                    Next
                                End If
                            End If
                        End With
                        lblFileInfo.Visible = False
                        lstTables.ContextMenuStrip = Nothing
                    Case 1
                        With dgExternal
                            .Rows.Clear()
                            .ColumnCount = 3
                            .ColumnHeadersVisible = True
                            .RowHeadersVisible = False
                            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                            .Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
                            .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
                            .Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                            .Columns(0).HeaderText = "Connection"
                            .Columns(1).HeaderText = "Server"
                            .Columns(2).HeaderText = "Database"
                            .Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
                            .Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
                            .Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
                            .AllowUserToResizeRows = False
                            .AllowUserToResizeColumns = False
                            .AllowUserToOrderColumns = False
                            .AllowUserToDeleteRows = False
                            .AllowUserToAddRows = False
                            .ReadOnly = True
                            .MultiSelect = False
                            .DefaultCellStyle.Font = New Font("Tahoma", 8.5, FontStyle.Regular, GraphicsUnit.Point)

                            For Each Connection As String In clsConnections.GetConnectionNames
                                With clsConnections.ConnectionInfo(Connection)
                                    dgExternal.RowCount += 1
                                    dgExternal.Item(0, dgExternal.RowCount - 1).Value = Connection
                                    dgExternal.Item(1, dgExternal.RowCount - 1).Value = .ServerAddress
                                    dgExternal.Item(2, dgExternal.RowCount - 1).Value = .DatabaseName
                                End With
                            Next
                            .Sort(.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
                            For r As Integer = 0 To .RowCount - 1
                                If .Item(0, r).Value = GetSetting(REGAPP, Me.Name, "Connection", "") Then
                                    .Rows(r).Selected = True
                                End If
                            Next
                        End With
                        lblFileInfo.Visible = False
                        lstTables.ContextMenuStrip = Nothing

                    Case 2
                        'set initial directory for browser...
                        lstTables.Items.Clear()
                        With ExplorerTree1
                            .ShowMyFavorites = False
                            .ShowMyNetwork = False
                            .ShowAddressbar = True
                            Dim PriorDir As String = GetSetting(REGAPP, Me.Name, "BrowserPath", "C:\")
                            If My.Computer.FileSystem.DirectoryExists(PriorDir) Then .setCurrentPath(PriorDir)
                        End With
                        lblFileInfo.Text = "Select file to get information here..."
                        lblFileInfo.Visible = True
                        lstTables.ContextMenuStrip = ContextMenuTables
                End Select
                Select Case TabControl1.SelectedIndex
                    Case 0, 3 : TabInitialized(TabControl1.SelectedIndex) = True 'will not change during session
                    Case 2 : TabInitialized(TabControl1.SelectedIndex) = False 'always want to refresh in case manage connections
                End Select
            End If

            'refresh tables/files list even if already initialized
            Select Case TabControl1.SelectedIndex
                Case 0 : GetTables(dgWRDB)
                Case 1 : GetTables(dgExternal)
                Case 2
                    ExplorerTree1.Visible = False
                    '_SuspendGetFiles = True 'need to artificially suspend because otherwise pathchanged event is fired many times and is slow
                    ExplorerTree1.btnGo_Click(Me, New System.EventArgs)
                    '_SuspendGetFiles = False
                    ExplorerTree1.Visible = True
                    GetFiles()
            End Select

            cboFileTypes.Visible = (TabControl1.SelectedIndex = 2)
            SplitTables.Panel2Collapsed = TabControl1.SelectedIndex <> 2
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    ''' <summary>
    ''' If file is selected that contains multiple dataset (e.g., MDB, XLS, etc), dataset list becomes visible and you can select which one
    ''' </summary>
    Private ReadOnly Property SelectedDatasets() As Generic.List(Of String)
        Get
            Dim lst As New Generic.List(Of String)
            For i As Integer = 0 To lstDatasets.SelectedItems.Count - 1
                lst.Add(lstDatasets.SelectedItems(i))
            Next
            Return lst
        End Get
    End Property

    ''' <summary>
    ''' Name of WRDB project that was selected (or path for non-WRDB file)
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private ReadOnly Property SelectedProjectName() As String
        Get
            Select Case TabControl1.SelectedIndex
                Case 0 : Return dgWRDB.SelectedCells(0).Value
                Case 1 : Return dgExternal.SelectedCells(0).Value
                Case Else
                    Return ExplorerTree1.SelectedPath
            End Select
        End Get
    End Property

    ''' <summary>
    ''' Type of project that was selected
    ''' </summary>
    Private ReadOnly Property SelectedProjectType() As enumProjectType
        Get
            Select Case TabControl1.SelectedIndex
                Case 0
                    Select Case dgWRDB.SelectedCells(1).Value
                        Case "6.x" : Return enumProjectType.WRDB6
                        Case "5.x" : Return enumProjectType.WRDB5
                        Case "4.x" : Return enumProjectType.WRDB4
                    End Select
                Case 1 : Return enumProjectType.External
                Case 2 : Return enumProjectType.File
                Case Else
                    Throw New IndexOutOfRangeException
            End Select
        End Get
    End Property

    ''' <summary>
    ''' Name of selected table or file (with extension)
    ''' </summary>
    Private ReadOnly Property SelectedTableName() As String
        Get
            Return lstTables.Text.Replace(" [Master]", "") 'in case is master table
        End Get
    End Property

    ''' <summary>
    ''' Type of table that was selected (Working or Master)
    ''' </summary>
    Private ReadOnly Property SelectedTableType() As enumTableType
        Get
            If lstTables.SelectedValue.ToString.Contains("[Master]") Then Return enumTableType.Master Else Return enumTableType.Working
        End Get
    End Property

    Public ReadOnly Property SelectedTables() As Generic.List(Of clsTable)
        Get
            Return _SelectedTables
        End Get
    End Property

    Private Sub mnuOpenContaining_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuOpenContaining.Click
        Process.Start(ExplorerTree1.SelectedPath)
    End Sub

    Private Sub btnManage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnManage.Click
        With New External.clsExternalData(Nothing)
            Dim ConName As String = ""
            If dgExternal.SelectedCells.Count > 0 Then ConName = dgExternal.SelectedCells(0).Value
            .ShowManageConnections(Me, ConName)
        End With
        GetProjects()
    End Sub

End Class